import DingTalkWorkflow_1_0, {
  StartProcessInstanceHeaders,
  StartProcessInstanceRequest,
  StartProcessInstanceRequestFormComponentValues,
} from '@alicloud/dingtalk/dist/workflow_1_0/client';
import Util, * as $Util from '@alicloud/tea-util';
import { getConfig } from '@libs/common/utils';

import { DingClientService } from './client.serivce';

const { DD } = getConfig();

export class DingWorkflowService extends DingClientService {
  constructor() {
    super();
  }

  private readonly client = new DingTalkWorkflow_1_0(this.createClient());

  async workflowOvertime(
    config: {
      originatorUserId: string;
      deptId: string;
      startDate: string;
      endDate: string;
      time: string;
      description: string;
      /** 申请订单记录 id */
      applyId: string;
    },
    accessToken: string,
  ) {
    const formComponentValues = [
      {
        id: '开始时间-结束时间',
        bizAlias: '',
        name: '["开始时间","结束时间"]',
        value: `["${config.startDate}","${config.endDate}"]`,
        componentType: 'DDDateRangeField',
      },
      {
        id: 'E58AA0E78FADE697B6E995BF',
        bizAlias: '',
        name: '加班时长',
        value: config.time,
        extValue: '',
        componentType: 'TextField',
      },
      {
        componentType: 'DDSelectField',
        name: '是否法定假日',
        id: '是否法定假日',
        value: '是',
        extValue: '{"label":"是","key":"option_K9CJV16M"}',
      },
      {
        componentType: 'DDSelectField',
        name: '加班核算方式',
        bizAlias: '',
        id: '加班核算方式',
        value: '申请调休',
        extValue: '{"label":"申请调休","key":"option_K9CJV16M"}',
      },
      {
        id: '加班原因',
        bizAlias: '',
        name: '加班原因',
        value: `${config.description} | ${config.applyId || '-'}`,
        extValue: '',
        componentType: 'TextField',
      },
    ].map((v) => new StartProcessInstanceRequestFormComponentValues(v));

    const { originatorUserId, deptId } = config;

    const startProcessInstanceRequest = new StartProcessInstanceRequest({
      originatorUserId: originatorUserId,
      processCode: 'PROC-EF6Y0XWVO2-RY49IDITM5OTY8U0Z1IV1-YT4ZX7MI-B3', // 加班申请
      deptId,
      microappAgentId: DD.DD_AgentId,
      formComponentValues: formComponentValues,
    });

    return this.create({ startProcessInstanceRequest }, accessToken);
  }

  /**
   * 发起审批实例
   * @link https://open.dingtalk.com/document/isvapp/initiate-approval-new
   */
  private async create(
    option: {
      startProcessInstanceRequest: StartProcessInstanceRequest;
    },
    accessToken: string,
  ) {
    const { startProcessInstanceRequest } = option;
    const headers = new StartProcessInstanceHeaders({});
    headers.xAcsDingtalkAccessToken = accessToken;

    try {
      const res = await this.client.startProcessInstanceWithOptions(
        startProcessInstanceRequest,
        headers,
        new $Util.RuntimeOptions({}),
      );

      if (res.statusCode !== 200) {
        throw new Error('更新卡片失败: ' + JSON.stringify(res.body));
      } else {
        return res.body;
      }
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        throw new Error(err.message);
      } else {
        throw new Error('更新卡片失败: ' + JSON.stringify(err));
      }
    }
  }
}
